package io.cloud.tec.project.component;

import io.cloud.tec.exception.ErrorResultException;
import io.cloud.tec.exception.RestApiRequestException;
import io.cloud.tec.project.enums.ResultEnum;
import io.cloud.tec.project.model.Result;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

public class RestApi {

    private static RestTemplate restTemplate;

    private static final String defaultAccountUrl = "https://chatgptmirror.com/api/v1/user/DefaultAccount";
    private static final String conversationUrl = "https://chatgptmirror.com/api/v1/conversation/ChatV2";

    private static final Integer success = 0;

    static {
        restTemplate = new RestTemplate();
    }

    public static <T> T account(Object req, Class<T> resultClazz) {
        return postForObject(defaultAccountUrl, req, resultClazz);
    }


    public static <T> T postForObject(String url, Object req, Class<T> resultClazz) {
        try {
            Result<T> result = restTemplate.postForObject(url, req, Result.class);
            if (result == null) {
                throw new ErrorResultException(ResultEnum.UNKNOWN);
            }
            if (success.equals(result.getCode())) {
                return result.getData();
            } else {
                throw new ErrorResultException(result.getCode(), result.getMessage());
            }
        } catch (RestClientException restClientException) {
            throw new RestApiRequestException("请求chatgpt的account接口异常", restClientException);
        }
    }

    public static String jdkDownloadLinkPageHtml() {
        try {
            String jdkDownloadPage = "https://www.oracle.com/java/technologies/javase/javase8-archive-downloads.html1";
            return restTemplate.getForObject(jdkDownloadPage, String.class);
        } catch (RestClientException restClientException) {
            throw new RestApiRequestException("请求jdkDownloadLinkPageHtml接口异常", restClientException);
        }
    }
}
